package com.google.code.bankagregator.adapter.bank.imex.parser.deposit;

import com.google.code.bankagregator.adapter.exception.AdapterConnectException;
import com.google.code.bankagregator.entities.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: kirill
 * Date: 14.06.13
 * Time: 2:54
 * To change this template use File | Settings | File Templates.
 */
public class ImexDepThreeWishesParser {
    private static final String DEPOSIT_URL = "http://imexbank.com.ua/rus/all_deps.phtml#3w";
    private static final int TBODY_TERM_INDEX = 1;
    private static final int TBODY_AMOUNT_INDEX = 3;
    private static final int TD_RATE_INDEX = 2;
    private Document con = null;
    private Bank bank = null;

    public ImexDepThreeWishesParser() throws AdapterConnectException {
        bank = new Bank();
        bank.setName("АО \"ИМЭКСБАНК\"");
        bank.setUrl("http://imexbank.com.ua/rus/main.phtml");
        try {
            con = Jsoup.connect(DEPOSIT_URL).timeout(5000).get();
        } catch (IOException e) {
            throw new AdapterConnectException(e.getMessage());
        }
    }

    /**
     * Get deposit`s params (Три желания)
     *
     * @return deposit`s params
     */
    public List<Deposit> getUAHDeposit() {
        List<Deposit> depositParam = new ArrayList<>();
        Pattern p = Pattern.compile("(“|”)");
        Matcher matcher = null;
        Element nameEl = con.select("div.about_content table").get(0).select("th").get(0);
        matcher = p.matcher(nameEl.text());
        String name = matcher.replaceAll("").trim();

        Integer[] tableLinesWithTerm = new Integer[]{0, 1, 2, 3};
        Integer[] listItemsWithAmount = new Integer[]{2, 4};

        for (int line : tableLinesWithTerm) {
            Deposit deposit = new Deposit();
            Element termEl = con.select("div.about_content table tbody").get(TBODY_TERM_INDEX).select("tr").
                    get(line).select("td:not([rowspan=4]) i").first();

            Elements rateEl = con.select("div.about_content table tbody").get(TBODY_TERM_INDEX).select("tr").
                    get(line).select("td:not([rowspan=4])").get(TD_RATE_INDEX).select("i");

            int term = Integer.parseInt(termEl.text().replaceAll("[^0-9.]+", "")) * 31;
            double rate = Double.parseDouble(rateEl.text().replace(",", ".").replace("%", ""));


            for (int item : listItemsWithAmount) {
                Element amountEl = con.select("div.about_content table tbody").get(TBODY_AMOUNT_INDEX).select("ul").
                        first().select("li").get(item);
                if (item == 2) {
                    String minAmountStr = amountEl.text().substring(24, 28);
                    int minAmount = Integer.parseInt(minAmountStr);
                    deposit.setMinAmount(minAmount);
                } else if (item == 4) {
                    String maxAmountStr = amountEl.text().substring(25, 34).replace(" ", "");
                    int maxAmount = Integer.parseInt(maxAmountStr);
                    deposit.setMaxAmount(maxAmount);
                }
            }

            deposit.setType(DepositType.Deposit);
            deposit.setDepositRate(rate);
            deposit.setRefill(true);
            deposit.setTerm(term);
            deposit.setName(name);
            deposit.setCurrency(Currency.UAH);
            deposit.setUrl(DEPOSIT_URL);
            deposit.setState(State.ACTIVE);
            deposit.setBank(bank);
            depositParam.add(deposit);
        }


        return depositParam;
    }
}

